package com.suoluo.zenadmin.common.tag;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class IntervalTag extends SimpleTagSupport{

	private Date from;
	private Date to;
	
	private long interval;
	
	public long getInterval() {
		return interval;
	}

	public void setInterval(long interval) {
		this.interval = interval;
	}

	public Date getFrom() {
		return from;
	}

	public void setFrom(Date from) {
		this.from = from;
	}

	public Date getTo() {
		return to;
	}

	public void setTo(Date to) {
		this.to = to;
	}

	@Override
	public void doTag() throws JspException, IOException {
		super.doTag();
		JspWriter out = getJspContext().getOut();
		if (interval > 0){
			out.print(formatInterval(TimeUnit.MINUTES.toMillis(interval)));
		} else {
			out.print(calcTimeInterval(from, to));
		}
	    
	}
	
	private String calcTimeInterval(Date from,Date to){
		
		if (from == null){
			return "";
		}
		long fromMills = from.getTime();
		long toMills = to == null ? System.currentTimeMillis() : to.getTime();
		long interval = toMills - fromMills;
		return formatInterval(interval);
	}
	
	private String formatInterval(long interval){
		if (interval < 0){
			return "";
		}
		long hours = TimeUnit.MILLISECONDS.toHours(interval);
		long mins = TimeUnit.MILLISECONDS.toMinutes(interval - TimeUnit.HOURS.toMillis(hours));
		StringBuilder format = new StringBuilder();
		if (hours > 0){
			format.append(hours).append("小时");
		}
		if (mins > 0){
			format.append(mins).append("分钟");
		}
		return format.toString();
	}
	
	
//	
//	public static void main(String []args){
//		
//		
//		Date to = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3) +- TimeUnit.MINUTES.toMillis(20));
//		Date from = new Date(System.currentTimeMillis());
////		long from = System.currentTimeMillis();
////		long to = System.currentTimeMillis() + 2 * 60 * 60 * 1000 + 300000;
////		 long hours = TimeUnit.MILLISECONDS.toHours(2 * 60 * 60 * 1000 + 300000);
////		 System.out.println(hours);
//		System.out.println(calcTimeInterval(to,from));
//	}
}
